package com.zxhtom.book.controller;

import com.zxhtom.book.config.model.BookConfig;
import com.zxhtom.book.model.Book;
import com.zxhtom.book.service.BookService;
import com.zxhtom.calculate.model.CustomUser;
import com.zxhtom.utils.IdUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Iterator;

/**
 * @author John
 */
@Controller
@RequestMapping(value="/book/file")
@Api(tags="book file",description="系统文件管理接口")
public class UploadController {

    @Autowired
    private BookService bookService;
    @Autowired
    private BookConfig bookConfig;
    /***
     *
     * 日志工具
     */
    public Logger logger = LogManager.getLogger(UploadController.class);

    @RequestMapping(value = "/uploads" , method = RequestMethod.POST)
    @ApiOperation(value = "多文件上传")
    public Integer uploads(HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.info("测试测试多文件上传@@@@zxh"+request.getParameter("cls"));
        //创建一个通用的多部分解析器
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //判断 request 是否有文件上传,即多部分请求
        if(multipartResolver.isMultipart(request)){
            //转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
            //取得request中的所有文件名
            Iterator<String> iter = multiRequest.getFileNames();
            while(iter.hasNext()){
                //记录上传过程起始时的时间，用来计算上传时间
                int pre = (int) System.currentTimeMillis();
                //取得上传文件
                MultipartFile file = multiRequest.getFile(iter.next());
                if(file != null){
                    //取得当前上传文件的文件名称
                    String myFileName = file.getOriginalFilename();
                    //如果名称不为“”,说明该文件存在，否则说明该文件不存在
                    if(myFileName.trim() !=""){
                        System.out.println(myFileName);
                        //重命名上传后的文件名
                        String fileName = "_" + file.getOriginalFilename();
                        //定义上传路径
                        String path = bookConfig.getRoot();
                        File localFile = new File(path,fileName);
                        if(!localFile.exists()){
                            localFile.createNewFile();
                            //localFile.mkdirs();
                        }
                        file.transferTo(localFile);
                        Book book = new Book();
                        book.setBookId(BigDecimal.valueOf(IdUtil.getInstance().getId()));
                        book.setBookClassId(getClsIdFromCookie(request));
                        book.setBookName(file.getOriginalFilename());
                        book.setBookUrl(fileName);
                        book.setUserName(((CustomUser)SecurityUtils.getSubject().getPrincipal()).getUserName());
                        bookService.insertBook(book);
                    }
                }
                //记录上传该文件后的时间
                int finaltime = (int) System.currentTimeMillis();
                System.out.println(finaltime - pre);
            }
        }
        return 1;
    }

    private BigDecimal getClsIdFromCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("cls".equals(cookie.getName().toString())) {
                    return BigDecimal.valueOf(Long.valueOf(cookie.getValue().toString()));
                }
            }
        }
        return BigDecimal.valueOf(0L);
    }
}
